package cn.bj.yu.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author 周宇
 * @create 2020-08-14 16:54
 * 求和计算的任务！
 * 3000 6000(ForkJoin) 9000(Stream并行流)
 * //如何使用forkjoin
 * //1、forkjoinPool 通过它来执行
 * //2、计算任务 forkjoinPool.execute(ForkJoinTask task)
 * //3、计算类要基继承 ForkJoinTask
 */
public class ForkJoinWork extends RecursiveTask<Long> {

    private Long start;//起始值
    private Long end;  //结束值
    private Long temp = 10000L;//临界值

    public ForkJoinWork(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    //计算方法 6000
    @Override
    protected Long compute() {
        Long lenth = (end - start);
        if (lenth <= temp) {
            //如果拆分完毕就相加
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else { //forjoin 递归
            //没有拆分完毕就开始拆分
            long middle = (start + end) / 2; //计算的两个值的中间值
            ForkJoinWork task1 = new ForkJoinWork(start, middle);
            task1.fork(); //拆分，并压入线程队列
            ForkJoinWork task2 = new ForkJoinWork(middle + 1, end);
            task2.fork(); //拆分，并压入线程队列

            //合并
            return task1.join() + task2.join();
        }
    }
}